package com.hwz.gulimall.member.service.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hwz.common.entity.GiteeUser;
import com.hwz.common.entity.OAuthToken;
import com.hwz.gulimall.member.entity.UserLoginVo;
import com.hwz.gulimall.member.exception.UserEmailExistException;
import com.hwz.gulimall.member.exception.UserNameExistException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.Query;

import com.hwz.gulimall.member.dao.MemberDao;
import com.hwz.gulimall.member.entity.MemberEntity;
import com.hwz.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void checkUserNameExist(String username) throws UserNameExistException {
        Integer i = this.getBaseMapper().selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (i > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkUserEmailExist(String email) throws UserEmailExistException {
        Integer i = this.getBaseMapper().selectCount(new QueryWrapper<MemberEntity>().eq("email", email));
        if (i > 0) {
            throw new UserEmailExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getUsername, userLoginVo.getUsername()).or()
                .eq(MemberEntity::getEmail, userLoginVo.getUsername()));
        if (memberEntity != null){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userLoginVo.getPassword(), memberEntity.getPassword());
            if (matches){
                return memberEntity;
            }else {
                return null;
            }
        }
        return null;
    }

    @Override
    public MemberEntity oauthLogin(OAuthToken oAuthToken) {

        String giteeUserMsgUrl = "https://gitee.com/api/v5/user?access_token=" + oAuthToken.getAccessToken();

        MemberEntity memberEntity;

        try {
            HttpResponse httpResponse = HttpRequest.get(giteeUserMsgUrl).execute();
            if (httpResponse.getStatus() != 200){
                log.error("gitee用户信息获取失败");
                return null;
            }
            String body = httpResponse.body();
            GiteeUser giteeUser = JSON.parseObject(body, GiteeUser.class);
            memberEntity = this.getBaseMapper().selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialUid, giteeUser.getId()));
            if (memberEntity != null){
                memberEntity.setAccessToken(oAuthToken.getAccessToken());
                memberEntity.setExpiresIn(oAuthToken.getExpiresIn());
                memberEntity.setLatestLoginTime(new Date());
                this.updateById(memberEntity);
            }else {
                //如果用户没有登录过进行注册
                memberEntity = new MemberEntity();
                memberEntity.setNickname(giteeUser.getName());
                memberEntity.setSocialUid(giteeUser.getId());
                memberEntity.setHeader(giteeUser.getAvatarUrl());
                memberEntity.setEmail(giteeUser.getEmail());
                memberEntity.setAccessToken(oAuthToken.getAccessToken());
                memberEntity.setExpiresIn(oAuthToken.getExpiresIn());
                memberEntity.setLatestLoginTime(new Date());

                this.save(memberEntity);
            }
            return memberEntity;
        } catch (HttpException e) {
            throw new RuntimeException(e);
        }
    }

}